<template>
  <div>
    <BasicTable @register="registerTable">
      <template #headerTop>
        <Alert v-if="checkedKeys.length > 0" type="info" show-icon style="position: relative">
          <template #message>
            <div>
              <span>已选中{{ checkedKeys.length }}条记录</span>
              <div style="position: absolute; top: 4px; right: 10px">
                <Tooltip title="删除">
                  <a-button type="text" @click="handleSelectedDelete">
                    <Icon :icon="ICON.DELETE" color="#0960bd" />
                  </a-button>
                </Tooltip>
              </div>
            </div>
          </template>
        </Alert>
      </template>
      <template #tableTitle>
        <FormItem :style="resourceSelectStyle">
          <span style="margin-right: 10px">资源库</span>
          <Select
            style="width: 150px"
            show-search
            v-model:value="resourceSelectValue"
            :options="resourceSelectList"
            :show-arrow="true"
          />
        </FormItem>
      </template>
      <template #toolbar>
        <Button class="mr-2" type="primary" @click="openAddResourceModal">添加资源</Button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column?.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'ant-design:edit-filled',
                tooltip: {
                  title: '编辑',
                  placement: 'top',
                },
                onClick: handleEdit.bind(null, record),
              },
              {
                icon: 'ant-design:eye-filled',
                tooltip: {
                  title: '详情',
                  placement: 'top',
                },
                onClick: openDetails.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                tooltip: {
                  title: '删除',
                  placement: 'top',
                },
                onClick: handleDelete.bind(null, record),
              },
            ]"
            :drop-down-actions="[
              {
                icon: 'material-symbols:download-2',
                tooltip: {
                  title: '下载资源',
                  placement: 'top',
                },
                onClick: handleDownload.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <BasicModal
      @register="registerModal"
      v-bind="$attrs"
      :helpMessage="['提示1', '提示2']"
      @ok="addResources"
    >
      <BasicForm @register="registerForm">
        <template #upLoadFileSlot>
          <Upload
            name="file"
            :beforeUpload="upLoadChange"
            :accept="acceptFile"
            v-model:file-list="fileList"
          >
            <Button>
              <Icon icon="material-symbols:upload" />
              上传文件
            </Button>
          </Upload>
        </template>
      </BasicForm>
    </BasicModal>
    <PublicDrawer
      @register="registerDrawer"
      @updateDescData="handleUpdateDescData"
      :show-tabs="['detail']"
    />
  </div>
</template>

<script lang="ts" setup>
  import { ICON } from '/@/enums/iconEnum';
  import { Alert, Tooltip } from 'ant-design-vue';
  import Icon from '/@/components/Icon/src/Icon.vue';

  import { ref, watch } from 'vue';
  import { useDrawer } from '/@/components/Drawer';
  import PublicDrawer from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import {
    resourceTableSchema,
    searchFormSchema,
    resourceSelectList,
    addResourceSelectList,
    detailSchema,
  } from './components/resource.data';
  import { resourcesParams } from '/@/api/thingsborad/resources/resourcesLibray/model/resourcesLibrayModel';
  import {
    getResourceList,
    addTheResource,
    deleteTheResource,
    downloadTheResource,
    editTheResource,
    getTheResourceInfo,
  } from '/@/api/thingsborad/resources/resourcesLibray/resourcesLibray';
  import { Button, FormItem, Select, Upload } from 'ant-design-vue';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { onMounted, nextTick } from 'vue';
  import dayjs from 'dayjs';
  import { ENTITY_TYPE } from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.data';
  import { tableFormStyleSetting, tableStyleSetting } from '/@/settings/thingsBoardDesign';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  const { createConfirm, createMessage } = useMessage();
  const checkedKeys = ref<any>([]);
  //接受上传文件类型
  let acceptFile = ref<string>('.js');
  let fileList = ref<any>([]);
  let isEdit = ref<boolean>(false);
  let editId = ref<string>();
  let resourcesTableData = ref<Array<any>>();
  let params = ref<resourcesParams>({
    pageSize: 10,
    page: 0,
    sortProperty: 'createdTime',
    sortOrder: 'DESC',
  });
  let resourceSelectStyle = ref<any>({
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  });
  // 上传文件类型
  let acceptClassify = {
    LWM2M_MODEL: '.xml',
    PKCS_12: '.pfx',
    JKS: '.jks',
    JS_MODULE: '.js',
  };
  let resourceSelectValue = ref<any>('All');
  let upLoadFile = ref<any>();
  let resourceSchemas: FormSchema[] = [
    {
      field: 'resourceType',
      component: 'Select',
      label: '资源类型',
      required: true,
      defaultValue: 'JS_MODULE',
      componentProps: {
        onclick: async () => {
          let formData = await validate();
          
          acceptFile.value = acceptClassify[formData.resourceType];
        },
        listHeight: 160,
        options: addResourceSelectList,
      },
    },
    {
      ifShow: (value) => {
        return value.model.resourceType === 'LWM2M_MODEL' ? false : true;
      },
      field: 'title',
      component: 'Input',
      label: '标题',
      required: true,

      componentProps: {
        placeholder: '请输入标题',
      },
    },
    {
      field: 'upLoadFile',
      component: 'Input',
      label: '上传资源文件',
      slot: 'upLoadFileSlot',
    },
  ];
  onMounted(() => {
    //初始化表格数据
    // 初始化弹窗
    setModalProps({
      title: '添加资源',
      okText: '添加',
      loading: false,
      confirmLoading: false,
      ...modalStyleSetting,
    });
    setProps({
      api: getResourceList,
      beforeFetch: (val) => {
        params.value.page = val.page - 1;
        params.value.pageSize = val.pageSize;
        params.value.sortOrder = val.order == 'ascend' ? 'ASC' : 'DESC';
        params.value.sortProperty = 'createdTime';

        if (val.deptName === null) {
          params.value.textSearch = undefined;
        } else {
          params.value.textSearch = val.deptName;
        }
        return params.value;
      },
      afterFetch: async (res) => {
        resourcesTableData.value = [];
        if (res.length === 0) {
          return resourcesTableData.value;
        }
        res.forEach((item) => {
          resourcesTableData.value?.push({
            createdTime: item.createdTime,
            title: item.title,
            resourceType: item.resourceType,
            etag: item.etag,
            resourceKey: item.resourceKey,
            id: item.id.id,
          });
        });
        return resourcesTableData.value;
      },
      fetchSetting: {
        pageField: 'page',
        sizeField: 'pageSize',
        listField: 'data',
        totalField: 'totalElements',
      },
    });
  });
  watch(
    () => resourceSelectValue.value,
    (nVal) => {
      setProps({
        api: getResourceList,
        beforeFetch: (val) => {
          params.value.page = val.page - 1;
          params.value.pageSize = val.pageSize;
          params.value.sortOrder = val.order == 'ascend' ? 'ASC' : 'DESC';
          params.value.sortProperty = 'createdTime';
          if (nVal === 'All') {
            params.value.resourceType = undefined;
          } else {
            params.value.resourceType = nVal;
          }
          if (val.deptName === null) {
            params.value.textSearch = undefined;
          } else {
            params.value.textSearch = val.deptName;
          }
          return params.value;
        },
        afterFetch: async (res) => {
          resourcesTableData.value = [];
          if (res.length === 0) {
            return resourcesTableData.value;
          }
          res.forEach((item) => {
            resourcesTableData.value?.push({
              createdTime: dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss'),
              title: item.title,
              resourceType: item.resourceType,
              etag: item.etag,
              resourceKey: item.resourceKey,
              id: item.id.id,
            });
          });
          return resourcesTableData.value;
        },
        fetchSetting: {
          pageField: 'page',
          sizeField: 'pageSize',
          listField: 'data',
          totalField: 'totalElements',
        },
      });
      reload();
    },
  );
  const [registerDrawer, { openDrawer }] = useDrawer();

  // 表单初始化
  const [registerForm, { validate, resetFields, updateSchema, setFieldsValue }] = useForm({
    layout: 'vertical',
    schemas: resourceSchemas,
    showSubmitButton: true,
    showResetButton: false,
    actionColOptions: {
      span: 24,
    },
    ...modalFormStyleSetting,
    showActionButtonGroup: false,
  });
  const [registerModal, { openModal, setModalProps, closeModal }] = useModal();
  //表格初始化
  const [registerTable, { reload, setProps }] = useTable({
    columns: resourceTableSchema,
    ...tableStyleSetting,
    formConfig: {
      layout: 'horizontal',
      schemas: searchFormSchema,
      showAdvancedButton: false,
      submitFunc: async () => {
        reload();
      },
      ...tableFormStyleSetting,
      actionColOptions: {
        md: { span: 8, offset: 16 },
        lg: { span: 6, offset: 16 },
        xl: { span: 4, offset: 16 },
        xxl: { span: 4, offset: 16 },
      },
    },

    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
    },
  });
  // 多选删除
  const handleSelectedDelete = () => {
    createConfirm({
      iconType: 'info',
      title: `确定要删除      '${checkedKeys.value.length}'     个资源吗？`,
      content: '请注意：确认后，资源及其所有相关数据将不可恢复。',
      onOk: async () => {
        for (const item of checkedKeys.value) {
          await deleteTheResource(item);
        }
        reload();
        checkedKeys.value = [];
      },
    });
  };

  // 多选
  function onSelect(record, selected) {
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, record.id];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => id !== record.id);
    }
  }
  // 全选
  function onSelectAll(selected, _selectedRows, changeRows) {
    const changeIds = changeRows.map((item) => item.id);
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, ...changeIds];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => {
        return !changeIds.includes(id);
      });
    }
  }
  function openDetails(record: Recordable) {
    openDrawer(true, {
      entityType: ENTITY_TYPE.RESOUCRCE_LIBRARY,
      entityId: record.id,
      api: getTheResourceInfo,
      title: record.title,
      detailSchema: detailSchema,
      params: record.id,
    });
  }
  async function handleEdit(record: Recordable) {
    fileList.value = [];
    isEdit.value = true;
    editId.value = record.id;
    setModalProps({
      title: '编辑资源',
      okText: '保存',
      loading: false,
      confirmLoading: false,
      ...modalStyleSetting,
    });
    openModal(true, true);

    nextTick(() => {
      fileList.value.push({
        uid: '',
        name: record.resourceKey,
        status: 'done',
        response: '',
        url: '',
      });

      updateSchema({
        field: 'resourceType',
        componentProps: {
          disabled: true,
        },
      });
      setFieldsValue({
        resourceType: record.resourceType,
        title: record.title,
      });
    });
  }
  async function handleDownload(record: Recordable) {
    try {
      const theResourceFileData = await downloadTheResource(record.id);
      const blob = new Blob([theResourceFileData], { type: 'text/plain' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = record.resourceKey; // 设置下载后的文件名
      document.body.appendChild(link); // 需要添加到DOM中才能触发点击事件
      link.click();
      document.body.removeChild(link); // 下载后移除元素
      window.URL.revokeObjectURL(url); // 释放内存
    } catch (error) {}
  }
  async function handleDelete(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定要删除资源      '${record.title}'     吗？`,
      content: '请注意：确认后，资源将不可恢复。',
      onOk: async () => {
        await deleteTheResource(record.id);
        reload();
      },
    });
  }
  async function addResources() {
    try {
      const validateValue = await validate();
      let data: any;
      if (isEdit.value) {
        data = await editTheResource(editId.value);
        data.title = validateValue.title;
        if (upLoadFile.value !== undefined) {
          data.data = upLoadFile.value.data;
          data.fileName = upLoadFile.value.fileName;
        }
      } else {
        if (upLoadFile.value.data === undefined) {
          createMessage.error('请上传资源文件');
          return;
        }
        data = {
          data: upLoadFile.value.data,
          fileName: upLoadFile.value.fileName,
          resourceType: validateValue.resourceType,
          title: validateValue.title === undefined ? '' : validateValue.title,
        };
      }
      await addTheResource(data);
      resetFields();
      reload();
      upLoadFile.value = {};
      fileList.value = [];
      closeModal();
    } catch (error) {}
  }
  const upLoadChange = (file: File) => {
    // 文件读取
    const reader = new FileReader();

    reader.readAsDataURL(file);
    //获取上传数据
    reader.addEventListener('load', () => {
      const base64: any = reader.result;
      fileList.value.forEach((item) => {
        item.status = 'done';
      });
      upLoadFile.value = {
        fileName: file.name,
        data: base64.split(',')[1],
      };
    });
  };

  function openAddResourceModal() {
    resetFields();
    upLoadFile.value = {};
    fileList.value = [];
    if (isEdit.value) {
      updateSchema({
        field: 'resourceType',
        componentProps: {
          disabled: false,
        },
      });
      isEdit.value = false;
    }
    openModal(true, true);
  }
  // 抽屉详情数据更改
  const handleUpdateDescData = (value) => {
    value.assetName = value.name;
    value.assetConfiguration = value.assetProfileName;
    value.label = value.label;
    value.customer = value.customerTitle;
    value.isOpen = value.customerIsPublic;
  };
</script>
